// Server1 is a minimal "echo" server.
package main

import (
	"fmt"
	"go_code/project02_bible/demo1.7_web服务/lissajous"
	"log"
	"net/http"
	"strconv"
	"strings"
	"sync"
)

// func test1() { //一个简单的web服务
// 	http.HandleFunc("/", handler) // each request calls handler
// 	log.Fatal(http.ListenAndServe("localhost:8000", nil))
// }

var mu sync.Mutex
var count int //感觉这个count是自增的,每次访问不做操作都增加1,做了++操作增加2

func main() {
	http.HandleFunc("/", handler)
	http.HandleFunc("/count", counter)
	http.HandleFunc("/1", handler1)
	http.HandleFunc("/2", func(w http.ResponseWriter, r *http.Request) { lissajous.Lissajous(w) })
	log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

// // handler echoes the Path component of the requested URL.
// func handler(w http.ResponseWriter, r *http.Request) {
// 	mu.Lock()
// 	count++
// 	mu.Unlock()
// 	fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
// }

// counter echoes the number of calls so far.
func counter(w http.ResponseWriter, r *http.Request) {
	mu.Lock()
	fmt.Fprintf(w, "Count %d\n", count)
	mu.Unlock()
}

// handler echoes the HTTP request.
func handler1(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto)
	for k, v := range r.Header {
		fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
	}
	fmt.Fprintf(w, "Host = %q\n", r.Host)
	fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr)
	if err := r.ParseForm(); err != nil {
		log.Print(err)
	}
	for k, v := range r.Form {
		fmt.Fprintf(w, "Form[%q] = %q\n", k, v)
	}
	fmt.Fprintf(w, "%v", r)
}

func handler(w http.ResponseWriter, r *http.Request) {
	mu.Lock()
	count++
	mu.Unlock()
	if strings.Contains(r.URL.Path, "=") {
		pos := strings.Index(r.URL.Path, "=")
		cycles, err := strconv.ParseFloat(r.URL.Path[pos+1:], 64)
		if err != nil {
			log.Print(err)
		}
		//fmt.Fprintf(w, "%f\n", cycles)
		lissajous.Lissajous1(w, cycles)
	} else {
		fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
	}

}
